package admin

import (
	"drama-go/internal/models/query"
	"drama-go/internal/module/admin/dto"
	"github.com/gin-gonic/gin"
	"github.com/worryry/8-pigeons/pkg/server/errcode"
	"github.com/worryry/8-pigeons/pkg/server/httpServer/response"
	"github.com/worryry/8-pigeons/pkg/server/router"
	util "github.com/worryry/8-pigeons/pkg/utils"
	"strconv"
	"time"
)

func init() {
	router.Register(&User{})
}

type User struct {
}

func (u User) Login(c *gin.Context) {
	params := dto.Login{}
	if err := c.ShouldBind(&params); err != nil {
		response.ToErrResponse(c, errcode.InvalidParams.WithDetails(err.Error()))
		return
	}
	q := query.Admin
	find, err := q.Where(q.Account.Eq(params.Account), q.Password.Eq(params.Password)).Debug().First()
	if err != nil {
		response.ToErrResponse(c, errcode.NotFound.WithDetails(err.Error()))
		return
	}
	token := util.EncodeMD5(find.Account + find.Password + strconv.FormatInt(time.Now().Unix(), 10) + util.GetRandomStr(25))

	_, err = q.Where(q.ID.Eq(find.ID)).Update(q.Token, token)
	if err != nil {
		response.ToErrResponse(c, errcode.BusinessError.WithDetails(err.Error()))
		return
	}
	response.ToSuccess(c, map[string]interface{}{
		"id":      find.ID,
		"avatar":  find.Avatar,
		"role_id": find.RoleID,
		"uuid":    find.ID,
		"token":   token,
	})
	return
}
